package com.ws.webpacket.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.view.View;

import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import com.tencent.smtt.sdk.WebViewClient;
import com.ws.webpacket.util.HLog;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;


public class WebClientOption {

    public static void initX5WebView(Context context) {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//                HLog.I("X5内核状态"+arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
//                HLog.I("X5内核初始化结束");
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(context.getApplicationContext(), cb);
    }


    private WebView webView;


    private WebViewLoadingListener webViewLoadingListener;//加载监听，只有界面首次显示时才使用，使用结束就移除
    private ActionListener actionListener;

    //选择上传图片相关
    private Activity mActivity;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public static final int FILECHOOSER_RESULTCODE = 0x106;
    public static final int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 0x107;

    public WebClientOption(Context context) {

        webView = new WebView(getFixedContext(context));

        webView.setBackgroundColor(Color.parseColor("#00000000"));
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);
        initWebView();
    }

    /**
     * 用于解决 Android 5.1.1 运行时无法创建 WebView
     * @param context
     * @return
     */
    public static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return context.createConfigurationContext(new Configuration());
        } else {
            return context;
        }
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }


    public WebView getWebView() {
        return webView;
    }


    //        	private static  String mHomeUrl = "http://app.html5.qq.com/navi/index";
//	   private static  String mHomeUrl = "http://soft.imtt.qq.com/browser/tes/feedback.html";
    private static String mHomeUrl = "http://debugtbs.qq.com";


    /**
     * 外部加载URL
     *
     * @param url
     */
    public void loadUrl(String url) {
        HLog.I("加载网页" + url);
        webView.loadUrl(url);
    }

    public boolean goBack() {
        if (webView.canGoBack()) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            webView.goBack(); //调用goBack()返回WebView的上一页面
            return true;
        }
        return false;
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
//            Logger.d("result:" + result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null : intent.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
//                Logger.d("result5:" + result);
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }

    public void setWebViewLoadingListener(WebViewLoadingListener webViewLoadingListener) {
        this.webViewLoadingListener = webViewLoadingListener;
    }

    public void removeWebViewLoadingListener() {
        this.webViewLoadingListener = null;
    }

    public void setActionListener(ActionListener actionListener) {
        this.actionListener = actionListener;
    }

    public interface WebViewLoadingListener {

        public void loading(int newProgress, String url);

        public void loadEnd(String msg);

        public void error(int code, String msg);

    }

    public interface ActionListener {

        public void newWiondow(WebClientOption webClientOption);

    }


    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许运行JavaScript
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //================X5WebView配置=================================
        webSettings.setSupportMultipleWindows(true);
        // webSettings.setLoadWithOverviewMode(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSettings.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        webSettings.setAppCachePath(webView.getContext().getDir("appcache", 0).getPath());
        webSettings.setDatabasePath(webView.getContext().getDir("databases", 0).getPath());
        webSettings.setGeolocationDatabasePath(webView.getContext().getDir("geolocation", 0)
                .getPath());
        // webSetting.setPreFectch(true);

        CookieSyncManager.createInstance(webView.getContext());
        CookieSyncManager.getInstance().sync();

        webView.setWebViewClient(client);
        webView.setWebChromeClient(chromeClient);
    }


    private WebViewClient client = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
//            HLog.I("开始加载"+url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            HLog.I("加载结束"+url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
//            HLog.I("加载资源"+url);
        }

        @SuppressWarnings("deprecation") 
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
//          Toast.makeText(webView.getContext(), "加载失败了,请选择其他线路", Toast.LENGTH_LONG).show();
        }

        @TargetApi(android.os.Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
            onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            HLog.I("shouldOverrideUrlLoading"+url);
            //开奖网判断   ||url.contains("open_lottery_mb/index.html")
            if (url.contains("&type=Browser")) {
//                //跳转浏览器
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                webView.getContext().startActivity(intent);
                return true;
            }else{
                webView.loadUrl(url);
                return true;
            }

//            if (url.contains("http:") || url.contains("https:")) {
//                webView.loadUrl(url);
//                return true;
//            } else {
//                try {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    webView.getContext().startActivity(intent);
//                } catch (Exception e) {
//
//                }
//                return true;
//            }
        }



        @Override
        public void onPageCommitVisible(WebView view, String url) {
            super.onPageCommitVisible(view, url);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, String url) {
//            HLog.I("shouldInterceptRequest "+url);
            return super.shouldInterceptRequest(webView, url);
        }

    };

    private WebChromeClient chromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // 获得网页的加载进度 newProgress为当前加载百分比

            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                webView.setVisibility(View.VISIBLE);
                if (webViewLoadingListener != null)
                    webViewLoadingListener.loadEnd(view.getUrl());
            } else {
                if (webViewLoadingListener != null) {
                    webViewLoadingListener.loading(newProgress, view.getUrl());
                } else {
//                    HLog.I("监听为空================================");
                }
            }
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialogb, boolean isUserGesture, Message message) {
//            HLog.I("onCreateWindow    新窗口消息结构："+message.toString());
            WebClientOption webClientOption = new WebClientOption(webView.getContext());

            WebView.WebViewTransport transport = (WebView.WebViewTransport) message.obj;
            transport.setWebView(webClientOption.getWebView());
            message.sendToTarget();

            if (actionListener != null) {
                actionListener.newWiondow(webClientOption);
            }

            return true;
        }

        @Override
        public void onCloseWindow(WebView webView) {
            super.onCloseWindow(webView);
        }

        @Override
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//            HLog.I("openFileChooser01   acceptType:" +acceptType+"   capture:"+capture);
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("*/*");
            i.setType(acceptType);
            if (acceptType != null) {
                i.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{acceptType});
            }
            mActivity.startActivityForResult(Intent.createChooser(i, "文件选择"), FILECHOOSER_RESULTCODE);
        }

        // For Android 5.0+
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//            HLog.I("openFileChooser02   acceptType:" +fileChooserParams.getAcceptTypes()+"   FilenameHint:"+fileChooserParams.getFilenameHint());
            mUploadMessageForAndroid5 = filePathCallback;
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);

            if (fileChooserParams.getAcceptTypes().length == 0) {
                contentSelectionIntent.setType("*/*");
            } else {
                String type = "";
                for (int i = 0; i < fileChooserParams.getAcceptTypes().length; i++) {
                    if (i > 0) {
                        type += ";";
                    }
                    type += fileChooserParams.getAcceptTypes()[i];
                }
                contentSelectionIntent.setType(type);
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "文件选择");

            mActivity.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
            return true;
        }

    };

}
